package kr.co.sdworld.webclient.spring.controller;

import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class DeviceTokenController 
{
	/***
	 *  클라이언트에서 알림을 승인할 시에 토큰을 저장하게 된다.
	 *  성공 실패 여부를 리턴해야 한다.
	 *  
	 *  p = {
	 *  	request : {
	 * 			token:"token value"
	 *  	}
	 *  }
	 *  result : {
	 *  	success:true/false
	 *  }
	 *  
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/saveToken")
	public ModelAndView saveToken( HttpServletRequest request, HttpServletResponse response)
	throws Exception
	{
		String p = getRequestBody( request);
		JsonFactory jsonFactory = new JsonFactory();
		
		HashMap<String,String> result = new HashMap<String,String>();
		result.put( "success", "true");
		ModelAndView mnv2 = new ModelAndView("jsonView");
		mnv2.addObject( "result", result);
		
		return mnv2;
	}
	
	protected String getRequestBody( HttpServletRequest request)
	{
		return request.getParameter( "p");
	}
	
	public static void main(String[] args) 
	{
		StringBuilder p = new StringBuilder();
		p.append( "{");
		p.append( "\"request1\":\"value1\",");
		p.append( "\"request2\":\"value2\"");
		p.append( "}");
		
		try 
		{
			ObjectMapper mapper = new ObjectMapper();
			JsonFactory jsonFactory = mapper.getJsonFactory();
			JsonParser parser = jsonFactory.createJsonParser( p.toString());
			JsonNode node = parser.readValueAsTree();
			
			for( Iterator<String> it = node.getFieldNames(); it.hasNext();)
			{
				String fieldName = it.next();
				System.out.println( fieldName + ":" + node.get(fieldName).asText());
			}
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
}
